import db from '../../db.js';
import _ from 'lodash';
const save = async (data) => {
  const [result] = await db.query('INSERT INTO `model`(`name`) values?', [data]);
  if (result?.affectedRows > 0) {
    return {
      affectedRows: result?.affectedRows,
      id: result?.insertId,
    };
  }
  return false;
};
const update = async (id, fields) => {
  const [result] = await db.query('update `model` set?  where id=?', [fields, id]);
  if (result?.affectedRows > 0) {
    return true;
  }
  return false;
};
const del = async (id) => {
  const [result] = await db.query('update   `model` set isDelete=1 where id=?', id);
  if (result?.affectedRows > 0) {
    return true;
  }
  return false;
};
function toTree(items) {
  let map = {};
  items.forEach((item) => {
    let field = {
      fieldId: item?.fieldId,
      name: item?.fieldName,
      label: item?.label,
      type: item?.type,
    };
    if (!map[item?.id]) {
      map[item?.id] = {
        id: item?.id,
        name: item?.name,
        list: _.isNil(field?.fieldId) ? [] : [field],
      };
    } else {
      if (!_.isNil(field?.fieldId)) {
        map[item?.id].list.push(field);
      }
    }
  });
  return Object.values(map);
}
const getList = async () => {
  const [rows] = await db.query(
    'SELECT model.id as id,model.name,fields.id as fieldId,fields.name as fieldName,fields.label,fields.type  FROM `model` LEFT JOIN `fields` ON model.id=fields.model_id WHERE model.isDelete=0 AND fields.isDelete=0',
  );

  return toTree(rows) || [];
};
const findById = async (id) => {
  const [row] = await db.query(
    'select  id,`name` from `model` where isDelete=0 and id=? limit 1',
    id,
  );
  return row || [];
};
export default {
  save,
  del,
  getList,
  findById,
  update,
};
